import React, { useRef } from "react";
import { Form, Input, DatePicker, Space, Button, Switch, Select, Upload } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import TheButton from "@/components/TheButton";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheDialog from "@/components/TheDialog";
import Editor from "./component/Editor";
import WageManage from "./component/sendcoupons"
import { getDateTime3 } from '@/utils/getDate';
import { apiGetCouponInfoPage, apiGetCouponInfoOpenOrClose, apiGetCouponInfoRemove, apiGetCouponInfoState } from '@/request/coupons'
import store from "@/store/store"
import moment from 'moment'
import _ from 'lodash'

const { RangePicker } = DatePicker;

const SearchHeader = ({ openDialog, getValue }) => {
  const formRef = useRef()
  const searchValue = store.getState().searchValue || {}
  const defaultoptions = searchValue.couponType === "J" ? "代金券" : searchValue.couponType === "Z" ? "折扣券" : searchValue.couponType === "D" ? "打车券" : "优惠券类型"
  const options = [
    {
      value: "J",
      label: '代金券'
    },
    {
      value: "Z",
      label: '折扣券'
    },
    {
      value: "D",
      label: '打车券'
    },
  ]
  const onFinish = (values) => {
    if (values.time && values.time.length) {
      values.createTimeStart = getDateTime3(values.time[0])
      values.createTimeEnd = getDateTime3(values.time[1])
    }
    delete (values.time)
    _.forIn(values, (v, k) => {
      if (!v) {
        delete (values[k])
      }
    })
    getValue(values)
  }
  const reset = () => {
    formRef.current.setFieldsValue({
      couponTitle: '',
      time: [],
      couponType: null
    })
    getValue({})
  }
  const download = (url) => {
    const eleLink = document.createElement('a');
    eleLink.style.display = 'none';
    // eleLink.target = "_blank"
    eleLink.href = url;
    // eleLink.download = url;
    // eleLink.href = record;
    document.body.appendChild(eleLink);
    eleLink.click();
    document.body.removeChild(eleLink);
  }
  return (
    <div
      className="p-search-box"
      style={{ display: "flex", justifyContent: "space-between" }}
    >
      <Form ref={formRef} onFinish={onFinish} layout="inline">
        <Form.Item name="couponTitle">
          <Input suffix={<SearchOutlined />} placeholder={"请输入优惠券名称"} defaultValue={searchValue.couponTitle} />
        </Form.Item>
        <Form.Item name="time" label="创建时间">
          <RangePicker format={'YYYY/MM/DD'} defaultValue={searchValue.hasOwnProperty('createTimeStart') ? [moment(searchValue.createTimeStart, 'YYYY/MM/DD'), moment(searchValue.createTimeEnd, 'YYYY/MM/DD')] : []} />
        </Form.Item>
        <Form.Item name="couponType">
          <Select options={options} style={{ width: 140 }} placeholder={defaultoptions} />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button htmlType="submit" type="primary">搜索</Button>
            <Button onClick={reset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>
      <TheButton haspermi={['coupons:list:add']} type="default" size="middle" onClick={openDialog}>
        新增优惠券
      </TheButton>
      <TheButton haspermi={['coupons:list:excel']} type="default" size="middle" onClick={() => { download("https://hqmimage.oss-cn-beijing.aliyuncs.com/%E7%94%B5%E8%AF%9D%E5%8F%B7%E6%A8%A1%E6%9D%BF.xlsx") }}>
        下载EXCEL模板
      </TheButton>
    </div>
  );
};

class List extends React.Component {
  state = {
    columns: [
      {
        title: "优惠券名称",
        dataIndex: "couponTitle",
        key: "couponTitle",
        render: (text, record) => {
          return <div className="p-white-space" style={{ width: 180 }}>{record.couponTitle}</div>
        }
      },
      {
        title: "优惠券类型",
        dataIndex: "couponType",
        key: "couponType",
        render: (text, record) => {
          let label = ''
          switch (text) {
            case 'J':
              label = '代金券';
              break;
            case 'Z':
              label = '折扣券';
              break;
            case 'D':
              label = '打车券';
              break;
          }
          return label;
        }
      },
      {
        title: "cdk关联",
        dataIndex: "cdKeyState",
        key: "cdKeyState",
        render: (text, record) => {
          if (text == 0) {
            return '启用'
          } else {
            return '未启用'
          }
        },
      },
      {
        title: "口令关联",
        dataIndex: "passwordState",
        key: "passwordState",
        render: (text, record) => {
          if (text == 0) {
            return '启用'
          } else {
            return '未启用'
          }
        },
      },
      {
        title: "口令",
        dataIndex: "password",
        key: "password",
        render: (text, record) => {
          if (text) {
            return text
          } else {
            return '/'
          }
        },
      },
      {
        title: "优惠内容",
        dataIndex: "couponPrice",
        key: "couponPrice",
        render: (text, record) => {
          if (record.couponType === 'J' || record.couponType === 'D') {
            return <React.$Price price={record.couponPrice} />
          }
          if (record.couponType === 'Z') {
            return `${React.$transNum(record.couponPrice, 1, -1)}折`
          }
        }
      },
      {
        title: "最大折扣金额",
        dataIndex: "couponMaxPrice",
        key: "couponMaxPrice",
        render: (text, record) => {
          if (record.couponType === 'Z' && record.couponMaxPrice !== -1) {
            return <React.$Price price={record.couponMaxPrice} />
          } else {
            return '/'
          }
        }
      },
      {
        title: "使用门槛",
        dataIndex: "usePrice",
        key: "usePrice",
        render: (text, record) => {
          if (record.usePrice === -1) {
            return <div>无条件限制</div>
          } else {
            return `满${React.$transNum(record.usePrice, 2, -2)}可用`
          }
        }
      },
      {
        title: "使用期限",
        render: (text, record) => {
          if (record.timeType === 1) {
            return <div>{record.effectiveTime}天</div>
          } else {
            return <div>{`${record.startTime}`} 至 {`${record.endTime}`}</div>
          }

        }
      },
      {
        title: "是否开启按天限领",
        dataIndex: "exchangeType",
        key: "exchangeType",
        render: (text, record) => {
          if (text == 0) {
            return '启用'
          } else {
            return '未启用'
          }
        }
      },
      {
        title: "限领",
        dataIndex: "xianling",
        key: "xianling",
        render: (text, record) => {
          return record.exchangeType == 0 ? (record.exchangeDays == -1 ? '不限制' : '每人' + record.exchangeDays + '日，限领' + record.exchangeCount + '张') : record.exchangeCount == -1 ? '不限制' : '每人限领' + record.exchangeCount + '张'
        }
      },
      {
        title: "状态",
        dataIndex: "couponStatus",
        key: "couponStatus",
        render: (text, record) => {
          let status = record.couponStatus === 'Y' ? 'N' : 'Y'
          let txt = record.couponStatus === 'Y' ? '禁用' : '启用'
          return <Switch onChange={() => this.switchChange(record.couponId, status, txt)} checked={record.couponStatus === 'Y'} />
        }
      },
      {
        title: "剩余张数",
        dataIndex: "couponStock",
        key: "couponStock",
        render: (text, record) => {
          if (parseInt(record.couponStock) === -1) {
            return '无限量'
          } else {
            return record.couponStock
          }
        }
      },
      {
        title: "创建时间",
        dataIndex: "createTime",
        key: "createTime",
      },
      {
        title: "操作",
        fixed: "right",
        render: (text, render) => {
          return (
            <div>
              {/* <TheButton onClick={() => this.openDialog('editor', render, render.couponId)}>修改</TheButton> */}
              <TheButton haspermi={['coupons:list:delete']} onClick={() => this.deleteConfirm(render.couponId)}>移除</TheButton>
              <TheButton haspermi={['coupons:list:CDkList']} onClick={() => this.viewCDKList(render.couponId)}>CDK列表</TheButton>
              <TheButton haspermi={['coupons:list:getRecord']} onClick={() => this.viewReceiptList(render.couponId)}>领取记录</TheButton>
              {render.couponStatus === 'Y' ? <TheButton haspermi={['coupons:list:sendCoupons']} onClick={() => this.sendDialog(render.couponId, render)}>发放优惠券</TheButton> : ""}

            </div>
          );
        },
      },
    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 0,
    visible: false,
    title: "",
    editorValue: null,
    searchValue: {},
    loading: false
  };
  async componentDidMount() {
    let searchParams = store.getState().searchValue
    let { pageNo, pageSize, searchValue ,pathName} = searchParams
   
    if (searchParams && pageNo && pathName == 'coupons') {
      this.setState({
        searchValue: {
          ...searchParams
        },
        pageData: {
          pageNo: pageNo, pageSize: pageSize
        }
      }, () => {
        this.getData()
      })
    } else {
      this.getData()
    }

  }
  viewCDKList = (couponId) => {
    this.props.history.push('/coupons/CDKlist/' + couponId)
  }
  viewReceiptList = (couponId) => {
    this.props.history.push('/coupons/Receipt/' + couponId)
  }
  sendDialog = (couponId, value) => {
    this.setState({
      couponId: couponId,
      indcutsValue: value,
      sendDialog: true
    })
  }
  sendhandleCancel = () => {
    this.setState({
      couponId: "",
      couponName: "",
      sendDialog: false
    });
  }
  getData = async () => {
    this.setState({ loading: true })
    const { pageData, searchValue } = this.state
    let params = {
      ...searchValue, ...this.state.pageData,
    }
    store.dispatch({
      type: 'SaveSearchValues',
      data: {
        pathName:'coupons',
        ...params
      }
    })
    let res = await apiGetCouponInfoPage({ ...params })
    // console.log(res.data)
    if (res.data && res.code === 0) {
      this.setState({
        pageData: {
          pageNo: res.pageNo,
          pageSize: res.pageSize,
        },
        total: res.totalCount,
        dataSource: res.data
      })
    }
    this.setState({
      loading: false
    })
  }
  getValue = value => {
    this.setState({
      searchValue: value,
      pageData: {
        pageNo: 1,
        pageSize: 10,
      },
    }, () => {
      this.getData()
    })
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo, pageSize
      }
    }, () => {
      console.log(this.state.pageData);
      this.getData()
    })
  };
  switchChange = (couponId, couponStatus, txt) => {
    React.$confirm({
      title: `您确定${txt}此优惠券吗？`,
      onOk: async () => {
        let res = await apiGetCouponInfoOpenOrClose({ couponId, couponStatus })
        if (res.code === 0) {
          await React.$message({
            type: 'info',
            content: `${txt}成功`
          })
          this.pageChange(1, 10)
        }
      }
    })
  }
  openDialog = (type, value, couponId) => {
    if (type === "editor") {
      this.setState({ title: "修改优惠券", visible: true, editorValue: value, couponId, type: 'editor' });
    } else {
      this.setState({ title: "添加优惠券", visible: true, editorValue: null, type: 'add' });
    }
  };
  handleCancel = () => {
    this.setState({
      title: "",
      visible: false,
      editorValue: null,
      type: 'add'
    });
  };
  deleteConfirm = (couponId) => {
    React.$confirm({
      title: "您确认移除此条优惠券信息吗？",
      onOk: async () => {
        let res = await apiGetCouponInfoState({ couponId })
        if (res.code === 0 && res.data.tips) {
          let arr = res.data.list.map(v => v.activityName)
          React.$confirm({
            title: `当前优惠券正在${arr.join(',')}中使用，是否删除？`,
            onOk: async () => {
              let res = await apiGetCouponInfoRemove({ couponId })
              if (res.code === 0) {
                React.$message({
                  type: 'info',
                  content: '移除成功'
                })
                this.getData()
              }
            }
          })
        } else {
          let res = await apiGetCouponInfoRemove({ couponId })
          if (res.code === 0) {
            React.$message({
              type: 'info',
              content: '移除成功'
            })
            this.getData()
          }
        }
      },
    });
  };
  render() {
    const {
      columns,
      dataSource,
      pageData: { pageNo, pageSize },
      total,
      visible,
      title,
      editorValue,
      type,
      couponId,
      loading,
      sendDialog,
      indcutsValue
    } = this.state;
    return (
      <div className="p-layout-box">
        <SearchHeader getValue={this.getValue} openDialog={() => this.openDialog("add")} />
        <div className="p-layout-content-pagination">
          <TheTable
            scroll={{ x: "max-content", y: '63vh' }}
            columns={columns}
            dataSource={dataSource}
            loading={loading}
          />
          <ThePagination
            pageNo={pageNo}
            pageSize={pageSize}
            total={total}
            pageChange={this.pageChange}
          />
        </div>
        <TheDialog
          title={title}
          visible={visible}
          footer={null}
          handleCancel={this.handleCancel}
          width={1200}

        >

          <Editor
            editorValue={editorValue}
            type={type}
            couponId={couponId}
            reload={this.getData}
            handleCancel={this.handleCancel} />


        </TheDialog>
        <TheDialog
          title={'指定用户发放优惠券'}
          visible={sendDialog}
          footer={null}
          handleCancel={this.sendhandleCancel}
          width={440}
        >
          <WageManage
            couponId={couponId}
            indcutsValue={indcutsValue}
            type={"indcuts"}
            handleCancel={this.sendhandleCancel} />
        </TheDialog>
      </div>
    );
  }
}

export default List;
